package com.ruoyi.system.service.impl.smy;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.smy.MallGoods;
import com.ruoyi.common.core.domain.smy.MallGoodsImage;
import com.ruoyi.system.mapper.smy.MallGoodsImageMapper;
import com.ruoyi.system.service.smy.IMallGoodsImageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MallGoodsImageServiceImpl implements IMallGoodsImageService {
	@Resource
	private MallGoodsImageMapper mallGoodsImageMapper;

	@Override
	public MallGoodsImage selectMallGoodsImageById(Long id) {
		return mallGoodsImageMapper.selectMallGoodsImageById(id);
	}

	@Override
	public List<MallGoodsImage> selectMallGoodsImageList(MallGoodsImage mallGoodsImage) {
		return mallGoodsImageMapper.selectMallGoodsImageList(mallGoodsImage);
	}

	@Override
	public int insertMallGoodsImage(MallGoodsImage mallGoodsImage) {
		return mallGoodsImageMapper.insertMallGoodsImage(mallGoodsImage);
	}

	@Override
	public int updateMallGoodsImage(MallGoodsImage mallGoodsImage) {
		return mallGoodsImageMapper.updateMallGoodsImage(mallGoodsImage);
	}

	@Override
	public int deleteMallGoodsImageByIds(Long[] ids) {
		return mallGoodsImageMapper.deleteMallGoodsImageByIds(ids);
	}

	@Override
	public int deleteMallGoodsImageById(Long id) {
		return mallGoodsImageMapper.deleteMallGoodsImageById(id);
	}

	@Override
	public void saveOrUpdateGoodsImage(MallGoods mallGoods, List<MallGoodsImage> goodsImageList) {
		MallGoodsImage queryImage = new MallGoodsImage();
		queryImage.setGoodsid(mallGoods.getId());
		List<MallGoodsImage> dbGoodsImageList = mallGoodsImageMapper.selectMallGoodsImageList(queryImage);
		Map<String,MallGoodsImage> dbGoodsImageMap = dbGoodsImageList.stream().collect(Collectors.toMap(MallGoodsImage::getName,a->a,(k1, k2)->k1));
		//保存图片集合，删除图片集合
		List<MallGoodsImage> saveList = CollectionUtil.newArrayList();
		List<MallGoodsImage> removeList = CollectionUtil.newArrayList();
		Map<String,MallGoodsImage> goodsImageMap = goodsImageList.stream().collect(Collectors.toMap(MallGoodsImage::getName,a->a,(k1, k2)->k1));
		//前端传回来的，系统中没有的，标记新增
		for(MallGoodsImage image : goodsImageList){
			if(!dbGoodsImageMap.containsKey(image.getName())){
				image.setGoodsid(mallGoods.getId());
				image.setMerchantId(mallGoods.getMerchantId());
				image.setCreatetime(new Date());
				saveList.add(image);
			}
		}
		//系统中存在的，前端传入没有的，标记为删除
		for(MallGoodsImage image : dbGoodsImageList){
			if(!goodsImageMap.containsKey(image.getName())){
				removeList.add(image);
			}
		}

		if(CollectionUtil.isNotEmpty(saveList)){
			saveList.forEach(item->mallGoodsImageMapper.insertMallGoodsImage(item));
		}
		if(CollectionUtil.isNotEmpty(removeList)){
			removeList.forEach(item->mallGoodsImageMapper.deleteMallGoodsImageById(item.getId()));
		}
	}
}
